package com.atguigu.gulimall.ssoserver.controller;

import com.sun.deploy.net.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @ClassName LoginController
 * @Description TODO
 * @Detail detail
 * @Author MyPC
 * @Date 2020/7/13
 * @Version 1.0
 */
@Controller
public class LoginController {

    @Autowired
    StringRedisTemplate redisTemplate;

    @GetMapping("/getInfo")
    @ResponseBody
    public String getInfo(@RequestParam("token") String token){
        String s = redisTemplate.opsForValue().get(token);
        return s;
    }

    /**
     * 跳转登录页
     * @return
     */
    @GetMapping("/login.html")
    public String loginPage(@RequestParam("redirect_url") String redirect, Model model,
                            @CookieValue(value = "sso_token",required = false) String cookieToken){
        //登录时，先判断该用户是否已经访问过单点登录系统进行登录了，如果登陆了，直接取出cookie返回即可
        if (!StringUtils.isEmpty(cookieToken)) {
            return "redirect:"+redirect+"?token="+cookieToken;
        }
        model.addAttribute("url",redirect);
        return "login";
    }

    /**
     * 登录操作
     * @return
     */
    @PostMapping("/userLogin")
    public String userLogin(String name, String password, String url, HttpServletResponse response){
        //如果未登录，先进行登录
        if(!StringUtils.isEmpty(name) && !StringUtils.isEmpty(password)){
            //随机key
            String uuid = UUID.randomUUID().toString();
            //1、向redis存储用户数据
            redisTemplate.opsForValue().set(uuid,name);
            //2、存储token到cookie中，这样所有请求访问单点登录系统时就会带上cookie
            Cookie cookie = new Cookie("sso_token",uuid);
            response.addCookie(cookie);
            //如果用户名和密码不为空，那么就认为登录成功,并且带回token，通过token值就可以获取到redis的数据
            return "redirect:"+url+"?token="+uuid;
        }else {
            //登录为成功，重新跳转到登录页
            return "login";
        }

    }
}
